package com.baidu.structure;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.structure.activity.AddContactActivity;
import com.baidu.structure.activity.LoginActivity;
import com.baidu.structure.constants.Keys;
import com.baidu.structure.constants.Tags;
import com.baidu.structure.db.DBManager;
import com.baidu.structure.fragments.ConversationFragment;
import com.baidu.structure.fragments.MarketFrament;
import com.baidu.structure.fragments.ContactFragment;
import com.baidu.structure.fragments.VideoFragment;
import com.baidu.structure.utils.ConfigUtils;
import com.baidu.structure.utils.JumpUtils;
import com.baidu.structure.utils.LogUtils;
import com.baidu.structure.utils.ToastUtils;
import com.baidu.structure.widgets.BottomNav;
import com.baidu.structure.widgets.ItemLinearLayout;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.ArrayList;

public class MainActivity extends BaseActivity implements BottomNav.OnBottomNavSelectedListener, View.OnClickListener {
    private BottomNav bottomNav;
    private int currentTabIndex = 0;
    private FragmentTransaction mTransaction;
    private ArrayList<Fragment> fragments;
    private SlidingMenu menu;

    //sliding menu related
    private ImageView userIconView;
    private TextView userNameView;
    private ItemLinearLayout changePswView;
    private ItemLinearLayout feedbackView;
    private ItemLinearLayout helpView;
    private ItemLinearLayout aboutView;
    private Button loginOutView;
    private Handler mHandler;
    public static final int LOGOUT_SUCCESS = 51;
    public static final int LOGOUT_FAIL = 50;
    private Toolbar toolbar;
    private TextView titleView;
    private Menu mMenu;
    private MenuItem item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        titleView = (TextView) findViewById(R.id.title_view);
        titleView.setText(getString(R.string.nav_bottom_conversation));
//        toolbar.setNavigationIcon(R.mipmap.nav_back);
        init();
        setSupportActionBar(toolbar);
        if (savedInstanceState != null) {
            currentTabIndex = savedInstanceState.getInt("selectedIndex", 0);
        }
    }

    private void init() {
        initSlidingMenu();
        bottomNav = (BottomNav) this.findViewById(R.id.bottomNav);
        bottomNav.setOnBottomNavSelectedListener(this);

        fragments = new ArrayList<>();
        fragments.add(new ConversationFragment());
        fragments.add(new ContactFragment());
        fragments.add(new MarketFrament());
        fragments.add(new VideoFragment());

        //init pages
        mTransaction = getSupportFragmentManager().beginTransaction()
                .add(R.id.container, fragments.get(0), Tags.FRAGEMNT_CONVERSATION)
                .add(R.id.container, fragments.get(1), Tags.FRAGEMNT_CONTACT)
                .add(R.id.container, fragments.get(2), Tags.FRAGEMNT_MARKET)
                .add(R.id.container, fragments.get(3), Tags.FRAGEMNT_VIDEO)
                .hide(fragments.get(0))
                .hide(fragments.get(1))
                .hide(fragments.get(2))
                .hide(fragments.get(3))
                .show(fragments.get(currentTabIndex));
        mTransaction.commit();

    }

    private void initSlidingMenu() {
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT);
        menu.setBehindOffset(200);
        View leftView = getLayoutInflater().inflate(R.layout.menu_left, null);
        initSlidingMenuContent(leftView);
        menu.setMenu(leftView);
        //attach to window
        menu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);
        menu.showMenu();
        menu.toggle();//toggle
    }

    private void initSlidingMenuContent(View v) {
        LogUtils.init("MineFragment");
        userIconView = (ImageView) v.findViewById(R.id.userIcon);
        userNameView = (TextView) v.findViewById(R.id.userName);
        changePswView = (ItemLinearLayout) v.findViewById(R.id.changePassword);
        feedbackView = (ItemLinearLayout) v.findViewById(R.id.feedback);
        helpView = (ItemLinearLayout) v.findViewById(R.id.help);
        aboutView = (ItemLinearLayout) v.findViewById(R.id.about);
        loginOutView = (Button) v.findViewById(R.id.login_out);

        userIconView.setOnClickListener(this);
        changePswView.setOnClickListener(this);
        feedbackView.setOnClickListener(this);
        helpView.setOnClickListener(this);
        aboutView.setOnClickListener(this);
        loginOutView.setOnClickListener(this);


        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
                switch (msg.what) {
                    case LOGOUT_SUCCESS:
                        //clear password
                        ConfigUtils.getDefaultInstance(MainActivity.this).write(Keys.LOGIN_PSW, "");
                        JumpUtils.simpleJump(MainActivity.this, LoginActivity.class);
                        break;
                    case LOGOUT_FAIL:
                        ToastUtils.simpleToast(MainActivity.this, getString(R.string.toast_logout_fail));
                        break;

                }
            }
        };
    }

    private void initData() {
        if (EMClient.getInstance().isLoggedInBefore()) {
            userIconView.setImageResource(R.mipmap.back);
            userNameView.setText(ConfigUtils.getDefaultInstance(this).readString(Keys.LOGIN_NAME));
        } else {
            userIconView.setImageResource(R.mipmap.unlogin);
            userNameView.setText(R.string.user_not_login);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        ConfigUtils.getDefaultInstance(this).registerEMListener();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("selectedIndex", currentTabIndex);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        currentTabIndex = savedInstanceState.getInt("selectedIndex", 0);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
        mMenu = menu;
        resetMenu();

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        //ToastUtils.simpleToast(this, item.toString());
        //noinspection SimplifiableIfStatement
        String itemName = item.getTitle().toString();
        if (itemName.equals("add")) {
            JumpUtils.simpleJump(this, AddContactActivity.class);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBottomNavClick(int index) {
        if (currentTabIndex == index) return;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
                .hide(fragments.get(currentTabIndex))
                .show(fragments.get(index));
        transaction.commit();
        currentTabIndex = index;

        //update toolbar
        switch (currentTabIndex) {
            case 0:
                titleView.setText(getString(R.string.nav_bottom_conversation));
                resetMenu();
                break;
            case 1:
                titleView.setText(getString(R.string.nav_bottom_contact));
                if (item != null) mMenu.removeItem(item.getItemId());
                item = mMenu.add(0, 1, 1, "add");
                if (DBManager.getInstance(MainActivity.this).queryInviteInfo().size() > 0) {
                    item.setIcon(R.mipmap.nav_plus_with_request);
                } else {
                    item.setIcon(R.mipmap.nav_plus);
                }
                item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
                break;
            case 2:
                titleView.setText(getString(R.string.nav_bottom_video));
                resetMenu();
                break;
            case 3:
                titleView.setText(getString(R.string.nav_bottom_market));
                resetMenu();
                break;
        }
        //ToastUtils.simpleToast(this, "your choose is:" + index);
    }

    private void resetMenu() {
        if (item != null) mMenu.removeItem(item.getItemId());
        item = mMenu.add(0, 1, 1, "设置");
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == Keys.LOGIN_REQUEST) {
            int index = data.getIntExtra(Keys.LOGIN, 0);
            if (currentTabIndex == index) return;
            onBottomNavClick(index);
            currentTabIndex = index;
        }
    }

    @Override
    public void onClick(View v) {
        if (v == userIconView) {
            JumpUtils.simpleJump(this, LoginActivity.class);
        } else if (v == changePswView) {

        } else if (v == feedbackView) {
        } else if (v == helpView) {
        } else if (v == aboutView) {
        } else if (v == loginOutView) {
            EMClient.getInstance().logout(true, new EMCallBack() {
                @Override
                public void onSuccess() {
                    mHandler.sendEmptyMessage(LOGOUT_SUCCESS);
                }

                @Override
                public void onError(int i, String s) {
                    LogUtils.e(s);
                    mHandler.sendEmptyMessage(LOGOUT_FAIL);
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });
        }
    }
}
